#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
#include <cmath>
#include"a.cpp"

using namespace cv;
using namespace std;
int main(){
    int frame_width = 640;
    int frame_height = 480;
    int minArea = 500; 
    
    Mat img = imread("/home/zhouzhenqi/桌面/class 13/test.jpeg");
    if (!img.empty()) {
        cout << "img is loaded" << endl;
        return -1;
    }
    
    // 高斯模糊
    resize(img, img, Size(frame_width, frame_height));
    GaussianBlur(img,img, Size(7, 7), 1.5); 
    
    Mat HSV_img;
    cvtColor(img, HSV_img, COLOR_BGR2HSV);
    
    int HUE_Min1 = 0, HUE_Max1 = 12, SAT_Min = 150, SAT_Max = 255, VALUE_Min = 120, VALUE_Max = 255;
    int HUE_Min2 = 168, HUE_Max2 = 179;
    
    namedWindow("HSV", WINDOW_FREERATIO);
    resizeWindow("HSV", Size(320, 280));
    
    createTrackbar("HUE_Min1", "HSV", &HUE_Min1, 179, Imgupdate);
    createTrackbar("HUE_Max1", "HSV", &HUE_Max1, 179, Imgupdate);
    createTrackbar("HUE_Min2", "HSV", &HUE_Min2, 179, Imgupdate);
    createTrackbar("HUE_Max2", "HSV", &HUE_Max2, 179, Imgupdate);
    createTrackbar("SAT_Min", "HSV", &SAT_Min, 255, Imgupdate);
    createTrackbar("SAT_Max", "HSV", &SAT_Max, 255, Imgupdate);
    createTrackbar("VALUE_Min", "HSV", &VALUE_Min, 255, Imgupdate);
    createTrackbar("VALUE_Max", "HSV", &VALUE_Max, 255, Imgupdate);
        
    while (1) {
        int h_min1 = getTrackbarPos("HUE_Min1", "HSV");
        int h_max1 = getTrackbarPos("HUE_Max1", "HSV");
        int h_min2 = getTrackbarPos("HUE_Min2", "HSV");
        int h_max2 = getTrackbarPos("HUE_Max2", "HSV");
        int s_min = getTrackbarPos("SAT_Min", "HSV");
        int s_max = getTrackbarPos("SAT_Max", "HSV");
        int v_min = getTrackbarPos("VALUE_Min", "HSV");
        int v_max = getTrackbarPos("VALUE_Max", "HSV");
        
        // 优化红色识别
        Mat mask = optimizeRedDetection(HSV_img, h_min1, h_max1, h_min2, h_max2, s_min, s_max, v_min, v_max);
                
        Mat result;
        bitwise_and(img, img, result, mask);
        
        // 寻找灯条
        vector<LightBar> lightBars = findLightBars(mask, minArea);
        
        // 匹配装甲板
        vector<ArmorPlate> armorPlates = matchArmorPlates(lightBars);
        
        if (armorPlates.size() > 2) {
            armorPlates.resize(2);
        }
        
        Mat detectionResult = drawDetectionResult(img, armorPlates);
        
        // 显示所有图像
        vector<Mat> images = {img, HSV_img, result, mask, detectionResult};
        display(images);
        
        // 按ESC键退出
        if (waitKey(1) == 27) exit(0);
    }
    
    destroyAllWindows();
    return 0;
}    